package com.cloud.upms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.cloud.api.upms.enums.RoleExceptionEnum;
import com.cloud.common.core.exception.ProjectException;
import com.cloud.common.core.result.Page;
import com.cloud.common.core.result.Result;
import com.cloud.common.log.annotation.SysLog;
import com.cloud.common.log.enums.OperateTypeEnum;
import com.cloud.api.upms.domain.role.RoleAddUpdateReq;
import com.cloud.api.upms.domain.role.RoleListReq;
import com.cloud.api.upms.model.SysRole;
import com.cloud.upms.service.SysRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import java.util.List;

/**
 * Author:  xuanning
 * Date:    2023/2/9 13:11
 */
@RestController
@AllArgsConstructor
public class SysRoleController {

    private final SysRoleService sysRoleService;

    /**
     * 新增
     * @return
     */
    @PostMapping(value = "/role/add")
    @SaCheckPermission(value = "role:add", orRole = "admin")
    @SysLog(title = "角色管理",operate = OperateTypeEnum.ADD)
    public Result<?> add(@Valid @RequestBody RoleAddUpdateReq paramReq) {
        paramReq.setId(null);
        sysRoleService.addOrUpdate(paramReq);
        return Result.success();
    }

    /**
     * 更新
     * @return
     */
    @PostMapping(value = "/role/update")
    @SaCheckPermission(value = "role:update", orRole = "admin")
    @SysLog(title = "角色管理",operate = OperateTypeEnum.UPDATE)
    public Result<?> update(@Valid @RequestBody RoleAddUpdateReq paramReq) {
        SysRole role=sysRoleService.getById(paramReq.getId());
        if(role==null){
            throw new ProjectException(RoleExceptionEnum.ROLE_NOT_EXIST);
        }
        sysRoleService.addOrUpdate(paramReq);
        return Result.success();
    }


    /**
     * 列表
     * @return
     */
    @PostMapping(value = "/role/list")
    @SaCheckPermission(value = "role", orRole = "admin")
    @SysLog(title = "角色管理",operate = OperateTypeEnum.UPDATE)
    public Result<?> listRole(@Valid @RequestBody RoleListReq param) {
        Page page=param.getPage();
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<SysRole> list=sysRoleService.listRole(param);
        return Result.page(list,page,new PageInfo(list).getTotal());
    }

    /**
     * 删除
     * @return
     */
    @GetMapping(value = "/role/delete")
    @SaCheckPermission(value = "role:delete", orRole = "admin")
    @SysLog(title = "角色管理",operate = OperateTypeEnum.DELETE)
    public Result<?> delete(Long id) {
        sysRoleService.delete(id);
        return Result.success();
    }


}
